package GUI;

import com.lowagie.text.pdf.hyphenation.TernaryTree;
import 数据库和网络.myDatebase;
import 试题和试卷.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

public class randomParameterWindow extends JFrame {
    public static JPanel mainPanel;
    public JButton detailButton,finishButton,confirmButton;
    public JLabel timeLabel,numLabel, nameLabel,difficultyLabel,label;
    ArrayList<question> questions;
    JFrame browze;
    static ArrayList<selectionQuestion>sellist;
    static ArrayList<definitionQuestion>deflist;
    static ArrayList<fillingblankQuestion>filllist;
    static ArrayList<subjectiveQuestion>sublist;

    static ArrayList<selectionAddItem>  selAdds;
    static ArrayList<definitionAddItem> defAdds;
    static ArrayList<fillingBlankAddItem> fillAdds;
    static ArrayList<subjectiveAddItem> subAdds;

    int papertime,questionnumber;
    Double maxDif,minDif;
    String nam;
    JTextArea time,min,max,number,name;

    public static void main(String[] args) {
        new randomParameterWindow();
    }
    public randomParameterWindow(){
        mainPanel = new JPanel();
        mainPanel.setLayout(null);

        confirmButton=new JButton("生成随机题组");


        difficultyLabel = new JLabel("难度区间：");
        label = new JLabel("—");
        min = new JTextArea(1,3);
        max = new JTextArea(1,3);
        nameLabel= new JLabel("试卷名称：");
        name=new JTextArea(1,10);
        timeLabel= new JLabel("考试时间：");
        time=new JTextArea(1,3);
        numLabel= new JLabel("题目数量：");
        number=new JTextArea(1,3);

        confirmButton.setBackground(Color.lightGray);
        confirmButton.addActionListener(new randomOrganizeListener());


        confirmButton.setBounds(67,240,120,30);

        nameLabel.setBounds(40,50,70,20);
        name.setBounds(110,50,100,30);
        timeLabel.setBounds(40,90,70,20);
        time.setBounds(110,90,100,30);
        numLabel.setBounds(40,130,70,20);
        number.setBounds(110,130,100,30);
        difficultyLabel.setBounds(40,170,70,20);
        min.setBounds(110,170,30,30);
        label.setBounds(153,170,30,30);
        max.setBounds(180,170,30,30);



        mainPanel.add(difficultyLabel);
        mainPanel.add(min);
        mainPanel.add(label);
        mainPanel.add(max);
        mainPanel.add(nameLabel);
        mainPanel.add(name);
        mainPanel.add(timeLabel);
        mainPanel.add(time);
        mainPanel.add(numLabel);
        mainPanel.add(number);

        mainPanel.add(confirmButton);




        this.setTitle("随机组卷参数");
        this.setContentPane(mainPanel);
        this.setSize(270,350);

        mainPanel.setSize(this.getSize());
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        //this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public class randomOrganizeListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            nam=name.getText();
            papertime=Integer.parseInt(time.getText());
            maxDif=Double.parseDouble(max.getText());
            minDif=Double.parseDouble(min.getText());
            questionnumber=Integer.parseInt(number.getText());
            myDatebase selQuery=new myDatebase("questioncollection");
            organizePaperWindow.selectionQuestions= new ArrayList<>();
            String sql="select * from questioncollection.selection_question";
            try {
                selQuery.statement.execute(sql);
                selQuery.resultSet=selQuery.statement.executeQuery(sql);

                while(selQuery.resultSet.next()){
                    String title=selQuery.resultSet.getString("questionTitle");
                    String text=selQuery.resultSet.getString("questiontext");
                    Double dif=selQuery.resultSet.getDouble("questiondifficulties");
                    int full=selQuery.resultSet.getInt("fullScore");
                    String a=selQuery.resultSet.getString("option_a");
                    String b=selQuery.resultSet.getString("option_b");
                    String c=selQuery.resultSet.getString("option_c");
                    String d=selQuery.resultSet.getString("option_d");
                    String answer= selQuery.resultSet.getString("answer");
                    question curr=new selectionQuestion(title,text,"selection",dif,full,answer);
                    curr.setOption_a(a);
                    curr.setOption_b(b);
                    curr.setOption_c(c);
                    curr.setOption_d(d);

                    organizePaperWindow.selectionQuestions.add((selectionQuestion) curr);

                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            sellist= new ArrayList<>();
            Iterator<selectionQuestion> selIte=organizePaperWindow.selectionQuestions.iterator();
            while(selIte.hasNext()) {
                selectionQuestion curr=selIte.next();
                if(curr.getDifficulty()>=minDif&&curr.getDifficulty()<maxDif)
                    sellist.add(curr);
            }

            organizePaperWindow.definitionQuestions = new ArrayList<>();
            sql = "select * from questioncollection.definition_question";
            try {
                selQuery.statement.execute(sql);
                selQuery.resultSet = selQuery.statement.executeQuery(sql);
                while (selQuery.resultSet.next()) {
                    String title = selQuery.resultSet.getString("questionTitle");
                    String text = selQuery.resultSet.getString("questiontext");
                    Double dif = selQuery.resultSet.getDouble("questionDifficulties");
                    int full = selQuery.resultSet.getInt("fullScore");
                    String right = selQuery.resultSet.getString("right");
                    String wrong = selQuery.resultSet.getString("wrong");
                    String answer = selQuery.resultSet.getString("answer");
                    question curr = new definitionQuestion(title, text, "definition", dif, full, answer);
                    curr.setRightOption(right);
                    curr.setWrongOption(wrong);

                    organizePaperWindow.definitionQuestions.add((definitionQuestion) curr);
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            deflist= new ArrayList<>();
            Iterator<definitionQuestion> defIte=organizePaperWindow.definitionQuestions.iterator();
            while(defIte.hasNext()) {
                definitionQuestion curr=defIte.next();
                if(curr.getDifficulty()>=minDif&&curr.getDifficulty()<maxDif)
                    deflist.add(curr);
            }

            organizePaperWindow.fillingblankQuestions= new ArrayList<>();
            sql="select * from questioncollection.fillingblank_question";
            try {
                selQuery.statement.execute(sql);
                selQuery.resultSet=selQuery.statement.executeQuery(sql);
                while(selQuery.resultSet.next()){
                    String title=selQuery.resultSet.getString("questionTitle");
                    String text=selQuery.resultSet.getString("questiontext");
                    Double dif=selQuery.resultSet.getDouble("questionDifficulties");
                    int full=selQuery.resultSet.getInt("fullScore");
                    String answer=selQuery.resultSet.getString("answer");
                    question curr=new fillingblankQuestion(title,text,"fillingBlank",dif,full,answer);
                    organizePaperWindow.fillingblankQuestions.add((fillingblankQuestion) curr);
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            filllist= new ArrayList<>();
            Iterator<fillingblankQuestion> fillIte=organizePaperWindow.fillingblankQuestions.iterator();
            while(fillIte.hasNext()) {
                fillingblankQuestion curr=fillIte.next();
                if(curr.getDifficulty()>=minDif&&curr.getDifficulty()<maxDif)
                    filllist.add(curr);
            }

            organizePaperWindow.subjectiveQuestions= new ArrayList<>();
            sql="select * from questioncollection.subjective_question";
            try {
                selQuery.statement.execute(sql);
                selQuery.resultSet=selQuery.statement.executeQuery(sql);
                while(selQuery.resultSet.next()){
                    String title=selQuery.resultSet.getString("questionTitle");
                    String text=selQuery.resultSet.getString("questiontext");
                    Double dif=selQuery.resultSet.getDouble("questionDifficulties");
                    int full=selQuery.resultSet.getInt("fullScore");
                    String answer=selQuery.resultSet.getString("answer");
                    question curr=new subjectiveQuestion(title,text,"subjective",dif,full,answer);
                    organizePaperWindow.subjectiveQuestions.add((subjectiveQuestion) curr);
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            sublist= new ArrayList<>();
            Iterator<subjectiveQuestion> subIte=organizePaperWindow.subjectiveQuestions.iterator();
            while(subIte.hasNext()) {
                subjectiveQuestion curr=subIte.next();
                if(curr.getDifficulty()>=minDif&&curr.getDifficulty()<maxDif)
                    sublist.add(curr);
            }
            int r=questionnumber/4,selnum=0,defnum=0,fillnum=0,subnum=0;
            switch (questionnumber%4){
                case 0-> {
                    selnum=r;
                    defnum=r;
                    fillnum=r;
                    subnum=r;
                }
                case 1->{
                    selnum=r+1;
                    defnum=r;
                    fillnum=r;
                    subnum=r;
                }
                case 2->{
                    selnum=r+1;
                    defnum=r+1;
                    fillnum=r;
                    subnum=r;
                }
                case 3->{
                    selnum=r+1;
                    defnum=r+1;
                    fillnum=r+1;
                    subnum=r;
                }
            }

            Random rand=new Random();
            int hel=0;

            questions= new ArrayList<>();
            int sellength,deflength,filllength,sublength;
            sellength=sellist.size();
            deflength=deflist.size();
            filllength= filllist.size();
            sublength=sublist.size();
            for(int i=1;i<=sellength-selnum;i++){

                    hel=rand.nextInt(sellist.size());
                    sellist.remove(hel);
            }
            for(int i=1;i<= deflength-defnum;i++){
                hel=rand.nextInt(deflist.size());
                deflist.remove(hel);
            }
            for(int i=1;i<= filllength-fillnum;i++){
                hel=rand.nextInt(filllist.size());
                filllist.remove(hel);
            }
            for(int i=1;i<= sublength-subnum;i++){
                hel=rand.nextInt(sublist.size());
                sublist.remove (hel);
            }

            for(int i=1;i<=sellist.size();i++){
                questions.add(sellist.get(i-1));
            }
            for(int i=1;i<=deflist.size();i++){
                questions.add(deflist.get(i-1));
            }
            for(int i=1;i<=filllist.size();i++){
                questions.add(filllist.get(i-1));
            }
            for(int i=1;i<=sublist.size();i++){
                questions.add(sublist.get(i-1));
            }
            selAdds=new ArrayList<>();
            defAdds=new ArrayList<>();
            fillAdds=new ArrayList<>();
            subAdds=new ArrayList<>();
            Iterator<selectionQuestion> selitelist=sellist.iterator();
            int index1=0;
            while(selitelist.hasNext()){
                question i=selitelist.next();
                ++index1;
                selAdds.add(new selectionAddItem(index1,i));
                //add(selList.get(t-1));
            }
            Iterator<definitionQuestion> defitelist=deflist.iterator();
            index1=0;
            while(defitelist.hasNext()){
                question i=defitelist.next();
                ++index1;
                defAdds.add(new definitionAddItem(index1,i));
                //add(selList.get(t-1));
            }
            Iterator<fillingblankQuestion> fillitelist=filllist.iterator();
            index1=0;
            while(fillitelist.hasNext()){
                question i=fillitelist.next();
                ++index1;
                fillAdds.add(new fillingBlankAddItem(index1,i));
                //add(selList.get(t-1));
            }
            Iterator<subjectiveQuestion> subitelist=sublist.iterator();
            index1=0;
            while(subitelist.hasNext()){
                question i=subitelist.next();
                ++index1;
                subAdds.add(new subjectiveAddItem(index1,i));
                //add(selList.get(t-1));
            }




            //organizePaperWindow.randomOrganize= new organizePaperWindow("haha");
            browze=new JFrame();
            JPanel panel = new JPanel();
            panel.setLayout(null);
            JLabel successLab=new JLabel();
            JButton i=new JButton("查看试题");
            JButton t=new JButton("返回");
            browze.setSize(200,220);
            browze.setContentPane(panel);

            String a="组卷成功！";
            successLab.setText(a);
            panel.setSize(browze.getSize());
            successLab.setFont(new Font("宋体" ,Font.BOLD,14));
            successLab.setBounds(62,20,100,30);
            i.setBackground(Color.lightGray);
            t.setBackground(Color.lightGray);
            i.setBounds(45,70,100,30);
            t.setBounds(45,110,100,30);
            i.addActionListener(new checkListener());
            t.addActionListener(new backListener());
            panel.add(successLab);
            browze.add(i);
            browze.add(t);
            browze.setLocationRelativeTo(null);//居中
            browze.setTitle("在线考试平台");
            browze.setVisible(true);

            randomParameterWindow.this.dispose();
        }
    }

    public class checkListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            browze.dispose();
            new organizePaperWindow(sellist,deflist,filllist,sublist,name.getText(),time.getText());
        }
    }

    public class backListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e){
            browze.dispose();
            myDatebase infoClass=new myDatebase("information_schema");
            myDatebase classFinder=new myDatebase("teacher");
            myDatebase resultCreator=new myDatebase("result_record");
            myDatebase paperUploader=new myDatebase("papercollection");
            ArrayList<String> classList=new ArrayList<>();
            ArrayList<String> realclasslist=new ArrayList<>();
            String sql;
            try {
                sql ="select * from INNODB_TABLES where NAME like '%papercollection%%class%'";
                infoClass.statement.execute(sql);
                infoClass.resultSet=infoClass.statement.executeQuery(sql);
                ArrayList<String> NamList=new ArrayList<>();
                while (infoClass.resultSet.next()){
                    String linshi=infoClass.resultSet.getString(2).substring(16);
                    classList.add(linshi);
                    System.out.println(linshi);
                }
                sql="select * from teacher.teacher where teacherID="+enterWindow.currentTeacher.getSchoolID()+"";
                classFinder.statement.execute(sql);
                classFinder.resultSet=classFinder.statement.executeQuery(sql);
                while(classFinder.resultSet.next()){
                    Iterator<String> ite=classList.iterator();
                    while(ite.hasNext()){
                        String j=ite.next();
                        if(classFinder.resultSet.getString(j).equals("true")){
                            realclasslist.add(j);
                            System.out.println(j);
                        }
                    }
                }

                sql=String.format("create table %s (questionText longtext,questionName char(20)," +
                        "questionPattern char(20),questionDifficulties double,fullScore int,answer longtext)",nam);
                paperUploader.statement.executeUpdate(sql);

                Iterator <selectionQuestion>selIte=sellist.iterator();
                while(selIte.hasNext()){
                    selectionQuestion st=selIte.next();
                    sql=String.format("insert into papercollection.%s (questiontext, questionname, questionpattern, questiondifficulties, fullscore, answer) " +
                            "values ('"+st.getText()+"','"+st.getTitle()+"','"+st.getType()+"','"+st.getDifficulty()+"','"+st.getFullScore()+"','"+st.getAnswer()+"')",nam);
                    paperUploader.statement.execute(sql);
                }

                Iterator<definitionQuestion>defIte=deflist.iterator();
                while(defIte.hasNext()){
                    definitionQuestion st=defIte.next();
                    sql=String.format("insert into papercollection.%s (questiontext, questionname, questionpattern, questiondifficulties, fullscore, answer) " +
                            "values ('"+st.getText()+"','"+st.getTitle()+"','"+st.getType()+"','"+st.getDifficulty()+"','"+st.getFullScore()+"','"+st.getAnswer()+"')",nam);
                    paperUploader.statement.execute(sql);
                }

                Iterator<fillingblankQuestion>fillIte=filllist.iterator();
                while(fillIte.hasNext()){
                    fillingblankQuestion st=fillIte.next();
                    sql=String.format("insert into papercollection.%s (questiontext, questionname, questionpattern, questiondifficulties, fullscore, answer) " +
                            "values ('"+st.getText()+"','"+st.getTitle()+"','"+st.getType()+"','"+st.getDifficulty()+"','"+st.getFullScore()+"','"+st.getAnswer()+"')",nam);
                    paperUploader.statement.execute(sql);
                }

                Iterator<subjectiveQuestion>subIte=sublist.iterator();
                while(subIte.hasNext()){
                    subjectiveQuestion st=subIte.next();
                    sql=String.format("insert into papercollection.%s (questiontext, questionname, questionpattern, questiondifficulties, fullscore, answer) " +
                            "values ('"+st.getText()+"','"+st.getTitle()+"','"+st.getType()+"',"+st.getDifficulty()+","+st.getFullScore()+",'"+st.getAnswer()+"')",nam);
                    paperUploader.statement.execute(sql);
                }



                Iterator<String> iet=realclasslist.iterator();
                while(iet.hasNext()){
                    String rel=iet.next();
                    sql=String.format("insert into papercollection.%s (paperTitle, limitedTime) values " +
                            "('"+nam+"',"+Integer.parseInt(time.getText())+")",rel);
                    paperUploader.statement.execute(sql);
                }
                //传到papercollection里每个class了

                sql="create table "+nam+"(studentID char(20),remainTime int,fillingblank_score int,subjective_score int,definition_score int,selection_score int)";
                resultCreator.statement.execute(sql);

                Iterator<definitionQuestion> defIter=deflist.iterator();
                while(defIter.hasNext()){
                    definitionQuestion currdef=defIter.next();
                    sql=String.format("alter table %s add column "+currdef.getTitle()+"_proper_answer char(20)",nam);
                    resultCreator.statement.execute(sql);
                    sql=String.format("alter table %s add column "+currdef.getTitle()+"_current_answer char(20)",nam);
                    resultCreator.statement.execute(sql);
                    //resultCreator.resultSet=resultCreator.statement.executeQuery(sql);
                }

                Iterator<selectionQuestion> selIter=sellist.iterator();
                while(selIter.hasNext()){
                    selectionQuestion currsel=selIter.next();
                    sql=String.format("alter table %s add column "+currsel.getTitle()+"_proper_answer char(20)",nam);
                    resultCreator.statement.execute(sql);
                    sql=String.format("alter table %s add column "+currsel.getTitle()+"_current_answer char(20)",nam);
                    resultCreator.statement.execute(sql);
                }
                Iterator<fillingblankQuestion> fillIter=filllist.iterator();
                while(fillIter.hasNext()){
                    fillingblankQuestion currfill=fillIter.next();
                    sql=String.format("alter table %s add column "+currfill.getTitle()+"_proper_answer longtext",nam);
                    resultCreator.statement.execute(sql);
                    sql=String.format("alter table %s add column "+currfill.getTitle()+"_current_answer longtext",nam);
                    resultCreator.statement.execute(sql);

                }
                Iterator<subjectiveQuestion> subIter=sublist.iterator();
                while(subIter.hasNext()){
                    subjectiveQuestion currsub=subIter.next();
                    sql=String.format("alter table %s add column "+currsub.getTitle()+"_proper_answer longtext",nam);
                    resultCreator.statement.execute(sql);
                    sql=String.format("alter table %s add column "+currsub.getTitle()+"_current_answer longtext",nam);
                    resultCreator.statement.execute(sql);
                    //resultCreator.resultSet=resultCreator.statement.executeQuery(sql);
                }

                sql=String.format("alter table %s add column is_revised char(20)",nam);
                resultCreator.statement.execute(sql);
                sql=String.format("update result_record.%s set is_revised='no'",nam);
                resultCreator.statement.execute(sql);

                ArrayList<String> stuID=new ArrayList<>();

                Iterator<String> clss=realclasslist.iterator();
                myDatebase stusel=new myDatebase("student");
                while(clss.hasNext()){
                    String cllaass=clss.next();
                    sql="select * from student.student where student.student.class='"+cllaass+"'";
                    stusel.statement.execute(sql);
                    stusel.resultSet=stusel.statement.executeQuery(sql);
                    while(stusel.resultSet.next()){
                        stuID.add(stusel.resultSet.getString(2));
                    }
                }

                Iterator<String> stuadd=stuID.iterator();
                while(stuadd.hasNext()){
                    String a=stuadd.next();
                    sql=String.format("insert into result_record.%s (studentID, remainTime) values ("+a+","+papertime*60+")",nam);
                    resultCreator.statement.execute(sql);
                }
                sql=String.format("update result_record.%s set %s_current_answer = 'a'",nam,questions.get(0).getTitle());
                resultCreator.statement.execute(sql);

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
